#include "debug_helper.h"

using namespace krryn;

#ifdef _WIN32

/* Needed for Dev-Cpp / FLASHWINFO combination */
#define WINVER 0x0501
#include <windows.h>

#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>

void core::redirect_io(int a_RedirectMode){
	int l_Connection;
	HWND hWnd = 0; //FindWindow("GLUT", WINDOW_TITLE);

	// open console and the main 
	// window to be on top of it
	AllocConsole();
	SetForegroundWindow(hWnd);

	// we're only  redirecting stdio so we need to 
	// sync all the c++ streams with that to get any 
	// output form them into the console
	std::ios::sync_with_stdio();

	if(a_RedirectMode & redirect_output){
		l_Connection = _open_osfhandle((intptr_t)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
		*stdout   = *_fdopen(l_Connection, "w");
		setvbuf(stdout, NULL, _IONBF, 0);
	}

	if(a_RedirectMode & redirect_input){
		l_Connection = _open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
		*stdin   = *_fdopen(l_Connection, "r");
		setvbuf(stdin, NULL, _IONBF, 0);
	}

	if(a_RedirectMode & redirect_error){
		l_Connection = _open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT);
		*stderr   = *_fdopen(l_Connection, "w");
		setvbuf(stderr, NULL, _IONBF, 0);
	}

	if(a_RedirectMode == redirect_none){
		FreeConsole();
	}
}

void core::notify(){
	HWND hWnd = 0; //FindWindow("GLUT", WINDOW_TITLE);
    
	// Flash the taskbar to let the user 
	// know we're done with something
	FLASHWINFO *l_Info = new FLASHWINFO();
    
	l_Info->cbSize  = sizeof(FLASHWINFO);
	l_Info->hwnd  = hWnd;
	l_Info->dwFlags  = FLASHW_ALL|FLASHW_TIMERNOFG;
	l_Info->uCount  = 1 << sizeof(UINT);
	l_Info->dwTimeout = 0;
    
	FlashWindowEx(l_Info);
}

#else

void core::redirect_io(int a_RedirectMode){
}

void core::notify(){
}

#endif
